package com.gzsxy.JUC.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 类型乐观锁
 * 如果期望的值有改动，会对比相应的版本
 */
public class CASDemo1 {


    public static void main(String[] args) {

        //AtomicStampedReference  1 期望值  1版本
        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(1, 1);


        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();//获取版本号
            System.out.println("a=>1 " + stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(atomicStampedReference.compareAndSet(1, 2,
                    atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));

            System.out.println("a2=> " + atomicStampedReference.getStamp());

            System.out.println(atomicStampedReference.compareAndSet(2, 1,
                    atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));


            System.out.println("a3=> " + atomicStampedReference.getStamp());
        }, "a").start();


        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();//获取版本号
            System.out.println("a=>2 " + stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(atomicStampedReference.compareAndSet(1, 6, stamp, stamp + 1));


        }, "a").start();
    }
}
